from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from django.conf import settings

from rest_framework.permissions import IsAuthenticated

from applet.utls import *


class AppletLoginView(APIView):
    """
    encryptedData, iv,code
    """

    def post(self, request):
        payload = dict()
        payload['return_code'] = 0
        payload['return_msg'] = 'Success'
        payload['return_data'] = ""
        code = request.POST.get("code")
        encryptedData = request.POST.get("encryptedData")
        iv = request.POST.get("iv")

        sessionkey = WXBizDataCrypt.get_sessionkey(code=code)

        if not sessionkey:
            payload['return_code'] = -1
            payload['return_msg'] = '获取sessionkey失败'
            payload['return_data'] = ""
            return Response(payload)
        applet = WXBizDataCrypt(settings.APPLET_APPID, sessionkey)
        response = applet.create_token(encryptedData, iv)
        if not response:
            payload['return_code'] = -1
            payload['return_msg'] = 'Invalid Buffer'
            payload['return_data'] = ""
            return Response(payload)
        return Response(response)


class wxAppletPayment(APIView):
    """
    orderid
    """
    permission_classes = [IsAuthenticated]

    def post(self, request):
        payload = dict()
        payload['return_code'] = 0
        payload['return_msg'] = 'Success'
        payload['return_data'] = ""
        orderid = request.POST.get("orderid")
        if not orderid:
            payload['return_code'] = -1
            payload['return_msg'] = '参数为空'
            payload['return_data'] = ""
            return Response(payload)
        user=request.suer
        goodsPrice="实际支付价格（订单价格）"
        goosName="商品名字"
        data=AppletPayment(user, orderid, goodsPrice, goosName)
        payload['return_data'] = data
        return Response(payload)

class PayToSaveView(APIView):

    def post(self,request):
        """
        保存支付结果
        :param request:
        :return:
        """
        reorder_result_xml = request.body.decode("utf-8")
        apple=appletpayStatus(reorder_result_xml)
        str = apple.verify_doc()
        return HttpResponse(str)